﻿using Sustainalytics.LongRunningTaskManager;
using Sustainalytics.LongRunningTaskManager.Interface;
using Sustainalytics.OAuth.Services.Common.Client;
using System;
using System.Net.Http;

namespace Sustainalytics.Insights.Tasks
{
    public class InsightsFileExportTask : ILongRunningTask
    {
        public LongRunningTaskTypeEnum Type
        {
            get { return LongRunningTaskTypeEnum.InsightsPDF; }
        }

        public object Start(LongRunningTaskContext context)
        {
            FileExportDto param = Newtonsoft.Json.JsonConvert.DeserializeObject<FileExportDto>(context.ParamJson);

            var file = GetFileResult(context, param.FileId);

            return file;
        }

        private ILongRunningTaskResult GetFileResult(LongRunningTaskContext context, string fileId)
        {
            OAuthClient oAuthClient = new OAuthClient(
                HostConfig.GetHostUrl() + HostConfig.GetFileResource() + "/token",
                HostConfig.GetHostUrl() + HostConfig.GetFileResource(),
                null,
                null);

            string reqPath = HostConfig.GetInsightsUrl() + HostConfig.GetFileResource() + "/" + fileId;

            oAuthClient.SetAuthenticationTicket(context.Ticket);

            HttpResponseMessage resp = oAuthClient.GetAsync(reqPath, context.CancellationToken).Result;

            resp.EnsureSuccessStatusCode();

            string fileName = resp.Content.Headers.ContentDisposition.FileName;
            string mimeType = resp.Content.Headers.ContentType.MediaType;
            byte[] contents = resp.Content.ReadAsByteArrayAsync().Result;

            var file = new LongRunningTaskFileInMemResult
            {
                FileName = fileName,
                MimeType = mimeType,
                Contents = contents
            };

            return file;
        }
    }
}
